package com.example.android10_socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements View.OnClickListener {

	InputStream is;
	OutputStream os;
	Socket socket;
	ObjectInputStream ois;
	ObjectOutputStream oos;
	TextView retMsg;
	EditText sendMsg;
	Button send;
	String rMsg;
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		setContentView(R.layout.activity_main);
		retMsg = (TextView)findViewById(R.id.retMsg);
		sendMsg = (EditText)findViewById(R.id.sendMsg);
		send = (Button)findViewById(R.id.send);
		send.setOnClickListener(this);
	}
	

	@Override
	public void onClick(View v) {
		start();
		retMsg.setText(rMsg);
	}
	
	public void start(){
		try {
			socket = new Socket("211.183.3.172",5005);
			sendMessage(socket);
			receiveMessage(socket);
		} 
		catch (Exception e){e.printStackTrace();}
		finally{
			try{socket.close();}catch(Exception e){e.printStackTrace();}
		}
	}
	
	private void receiveMessage(Socket socket2) {
		try {
			is = socket2.getInputStream();
			ois = new ObjectInputStream(is);
			rMsg = (String)ois.readObject();
		} 
		catch (Exception e) {e.printStackTrace();}
	}

	private void sendMessage(Socket socket2) {
		try {
			os = socket2.getOutputStream();
			oos = new ObjectOutputStream(os);
			String sMsg = sendMsg.getText().toString();
			oos.writeObject(sMsg);
		} 
		catch (Exception e) {e.printStackTrace();}
		
	}
	
	
	
	

}
